#include "GeneralReceivingQueue.h"
#include <string.h>
GeneralReceivingQueueItem_t * _queueHead = (GeneralReceivingQueueItem_t*)0;


void GeneralReceivingQueueAddItem(GeneralReceivingQueueItem_t *item,unsigned short timeout)
{
	GeneralReceivingQueueItem_t * tmp;
	item->count      = 0;
	item->timeout    = timeout;
	item->timeoutCnt = 0;
	if(_queueHead == (GeneralReceivingQueueItem_t*)0)
	{
		_queueHead = item;
	}
	else
	{
		tmp = _queueHead;
		while(tmp->next != (GeneralReceivingQueueItem_t*)0)
		{
			tmp = tmp->next;
		}
		tmp->next = item;
	}
}


void GeneralReceivingQueueTimeout(void)
{
	GeneralReceivingQueueItem_t * tmp = _queueHead;
	for(tmp = _queueHead;tmp != (GeneralReceivingQueueItem_t*)0;tmp = tmp->next)
	{
		if(tmp->isRecvCompleted == 1)
		{
			tmp->timeoutCnt = 0;
		}
		else if(tmp->idx)
		{
			tmp->timeoutCnt++;
		}
		if(tmp->idx > 0 && tmp->isRecvCompleted == 0 && tmp->timeout <= tmp->timeoutCnt)
		{
			tmp->isRecvCompleted = 1;
			tmp->count           = tmp->idx;
			tmp->idx             = 0;
			tmp->timeoutCnt      = 0;
		}
	}
}

void GeneralReceivingQueueGetByte(GeneralReceivingQueueItem_t* queue,unsigned char byte)
{
	if(!queue->isRecvCompleted && queue->idx < GENERAL_QUEUE_RECV_BUFF_SIZE)
	{
		queue->buff[queue->idx] = byte;
		queue->idx++;
		queue->timeoutCnt      = 0;
	}
}
unsigned short GeneralReceivingQueueGetBuff(GeneralReceivingQueueItem_t* queue,unsigned char *buff)
{
	if(queue->isRecvCompleted)
	{
		memcpy(buff,queue->buff,queue->count);
		queue->isRecvCompleted = 0;
		return queue->count;
	}
	return 0;
}